<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="className" style="width: 240px">
        <el-select v-model="queryParams.className" @change="changeStudentList" placeholder="请选择班级"
                   :style="{width: '100%'}">
          <el-option v-for="(item, index) in classesList" :key="index" :label="item.className"
                     :value="item.className"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="阶段" prop="stage" style="width: 240px">
        <el-select v-model="queryParams.stage" placeholder="请选择阶段" clearable>
          <el-option
            v-for="dict in sys_stage"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="日期" prop="date">
        <el-date-picker clearable
                        v-model="queryParams.date"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="第几天" prop="day">
        <el-input
          v-model="queryParams.day"
          placeholder="请输入第几天"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          size="small"
          @click="handleAddPlan"
          v-hasPermi="['teaching:plan:add']"
        >设计教学计划
        </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange"
              :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="日期" align="center" prop="date" fixed="left">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="班级名字" align="center" prop="className"/>
      <el-table-column label="阶段" align="center" prop="stage">
        <template #default="scope">
          <dict-tag :options="sys_stage" :value="scope.row.stage"/>
        </template>
      </el-table-column>

      <el-table-column label="周几" align="center" prop="weekday">
        <template #default="scope">
          <dict-tag :options="ya_weekday" :value="scope.row.weekday"/>
        </template>
      </el-table-column>

      <el-table-column label="第几天" align="center" prop="day"/>
      <el-table-column label="授课内容" align="center" prop="courseContent"/>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <el-table-column label="班主任记录" align="center" prop="patrolAndCommunicationRecord"/>
      <el-table-column label="整体学习情况" align="center" prop="studentLearningStatus"/>
      <el-table-column label="出席/缺席/迟到/请假" align="center" prop="stage" width="200px">
        <template #default="scope">
          {{ scope.row.presentCount }}/{{ scope.row.absentCount }}/{{ scope.row.lateCount }}/{{
            scope.row.excusedCount
          }}
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        label="操作"
        width="260px">
        <template #default="scope">
          <el-button v-show="scope.row.courseContent!='周日休息' && scope.row.courseContent!='自习'"
                     size="small"
                     type="primary"
                     :icon="Search"
                     @click="checkDailyTask(scope.row)"
                     v-hasPermi="['teaching:tasks:edit']"
          >每日任务
          </el-button>

          <el-button v-show="scope.row.courseContent!='周日休息'" @click="handleAddTracking(scope.row)" type="success"
                     size="small">教学跟踪
          </el-button>

          <el-button v-show="scope.row.courseContent!='周日休息'" @click="handleAddAttendance(scope.row)" type="warning"
                     size="small">考勤
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :page-sizes="[200,500]"
      :page-size="200"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 任务完成情况对话框 -->
    <el-dialog title="每日任务完成情况" v-model="completionOpen" fullscreen>
      <el-form :inline="true" ref="completionFormRef" class="demo-form-inline" :model="completionForm"
               :rules="completionRules" label-width="80px">
        <el-form-item label="完成状态" prop="status">
          <el-select v-model="completionForm.status" placeholder="请选择完成状态" clearable>
            <el-option
              v-for="dict in ya_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学生名字" prop="status">
          <el-input v-model="completionForm.studentName">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="checkDailyTask">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="completionLoading" style="width: 100%" :data="completionList">
        <el-table-column label="学生名字" align="center" prop="studentName">
        </el-table-column>

        <el-table-column label="学生账号" align="center" prop="username">
        </el-table-column>

        <el-table-column label="任务状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="ya_task_status" :value="scope.row.status"/>
          </template>
        </el-table-column>

        <el-table-column label="日期" align="center" prop="date">
        </el-table-column>

        <el-table-column label="总结图片" align="center" prop="summaryPicUrl">
          <template #default="scope">
            <el-image v-if="scope.row.summaryPicUrl"
                      style="width: 50px; height: 50px"
                      :src="`${baseUrl}${scope.row.summaryPicUrl}`"
                      :preview-src-list="preList(baseUrl+scope.row.summaryPicUrl)">
            </el-image>
            <span v-else>未上传</span>
          </template>
        </el-table-column>

        <el-table-column label="难点反馈" align="center" prop="difficultyFeedback"/>
        <el-table-column label="是否合格" align="center" prop="qualified">
          <template #default="scope">
            <el-select v-model="scope.row.qualified" clearable @change="updateQualified(scope.row)">
              <el-option
                v-for="dict in ya_task_qualified"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template #default="scope">
            <el-button v-show="scope.row.courseContent!='周日休息'"
                       size="small"
                       type="primary"
                       :icon="Search"
                       @click="checkInterview(scope.row)"
                       v-hasPermi="['teaching:tasks:edit']"
            >查看面试题
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelCompletion">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
      title="面试题练习情况"
      v-model="drawer"
      direction="ltr"
      :before-close="handleClose"
      size="80%">
      <el-card class="box-card" v-for="(interview,index) in interviewList" :key="index">
        <el-form ref="formRef" :model="interviewForm" :rules="rules" label-width="80px">
          <el-form-item :label="'题目'+(index+1)">
            {{ interview.question }}
          </el-form-item>

          <el-form-item label="答案" prop="answer">
            <el-input v-model="interview.answer" :id="'answer'+interview.interviewId" autosize
                      :ref="el => answerRefs['answer'+interview.interviewId] = el" type="textarea"
                      onpaste="return false;" placeholder="答案"/>
          </el-form-item>

          <el-form-item label="参考答案" prop="answer" v-if="interview.referenceAnswer">
            <mavon-editor v-model="interview.referenceAnswer" :subfield="false" defaultOpen="preview" :editable="false"
                          :toolbarsFlag="false"/>
          </el-form-item>

          <el-form-item label="难点" prop="difficulty" v-if="interview.difficulty">
            <el-input v-model="interview.difficulty" type="textarea" autosize onpaste="return false;"
                      placeholder="对于参考答案哪里不理解"/>
          </el-form-item>

          <el-form-item label="what" prop="what" v-if="interview.what">
            <el-input v-model="interview.what" type="textarea" autosize onpaste="return false;" placeholder="是什么"/>
          </el-form-item>

          <el-form-item label="how" prop="how" v-if="interview.how">
            <el-input v-model="interview.how" type="textarea" autosize onpaste="return false;" placeholder="怎么用"/>
          </el-form-item>

          <el-form-item label="why" prop="why" v-if="interview.why">
            <el-input v-model="interview.why" type="textarea" autosize onpaste="return false;" placeholder="有什么用"/>
          </el-form-item>

          <el-form-item label="if when" prop="ifThen" v-if="interview.ifThen">
            <el-input v-model="interview.ifThen" type="textarea" autosize onpaste="return false;"
                      placeholder="什么场景下用"/>
          </el-form-item>
        </el-form>
      </el-card>
    </el-drawer>

    <el-dialog title="智能生成教学计划" v-model="open" width="90%" fullscreen>
      <el-form :inline="true" class="demo-form-inline" ref="formRef" :model="form" :rules="rules" size="default"
               label-width="120px">
        <el-form-item label="班级" prop="className" style="width: 240px">
          <el-select v-model="form.className" @change="changeStudentList" placeholder="请选择班级"
                     :style="{width: '100%'}">
            <el-option v-for="(item, index) in classesList" :key="index" :label="item.className"
                       :value="item.className"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="阶段" prop="stage" style="width: 240px">
          <el-select v-model="form.stage" placeholder="请选择阶段" clearable>
            <el-option
              v-for="dict in sys_stage"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="阶段开始时间">
          <el-date-picker
            v-model="form.beginDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="queryTeachingPlan"> 查询已有计划
          </el-button>
          <el-button type="warning" :icon="Scissor" size="default" @click="handlePreviewTeachingPlan"> 重新创建预览
          </el-button>
          <el-button type="danger" :icon="Calendar" size="default" @click="handleClearConfig"> 重置调休配置</el-button>
          <el-button
            type="danger"
            :icon="Delete"
            @click="handleDelete"
            v-hasPermi="['teaching:plan:remove']"
          >删除
          </el-button>
        </el-form-item>

        <el-table
          :data="planAllList"
          @selection-change="handleSelectionChange"
          :row-key="row => row.id"
          style="width: 100%"
          :row-class-name="tableRowClassName">
          <el-table-column
            type="selection"
            width="55"
            align="center">
          </el-table-column>
          <el-table-column
            prop="date"
            label="日期"
            width="180">
          </el-table-column>

          <el-table-column
            prop="className"
            label="班级">
          </el-table-column>

          <el-table-column
            prop="stage"
            label="阶段">
            <template #default="scope">
              <dict-tag :options="sys_stage" :value="scope.row.stage"/>
            </template>
          </el-table-column>

          <el-table-column
            prop="weekday"
            label="周几"
            width="90">
            <template #default="scope">
              <dict-tag :options="ya_weekday" :value="scope.row.weekday"/>
            </template>
          </el-table-column>

          <el-table-column
            prop="day"
            label="第几天">
          </el-table-column>

          <el-table-column
            prop="courseContent"
            label="课程内容"
            width="180">
            <template #default="scope">
              <el-input v-model="scope.row.courseContent"></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="remarks"
            label="备注"
            width="180">
            <template #default="scope">
              <el-input v-model="scope.row.remarks"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                size="small"
                type="success"
                @click="handleAddHoliday(scope.$index, scope.row,'休息')" v-if="!isHoliday(scope.row)">休息
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="handleAddHoliday(scope.$index, scope.row,'自习')" v-if="!isHoliday(scope.row)">自习
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleAddWorkday(scope.$index, scope.row)"
                v-if="isHoliday(scope.row) && !scope.row.courseContent.includes('节')">上课
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <div>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">提交修改</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="添加教学跟踪信息" v-model="tracking_open" width="500px" fullscreen>
      <el-form ref="trackingFormRef" :model="trackingForm" :rules="rules" label-width="180px">
        <el-form-item label="未完成作业及未反馈名单" prop="unfinishedHomeworkAndUnfeedbackList">
          <el-input v-model="trackingForm.unfinishedHomeworkAndUnfeedbackList" type="textarea"
                    placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="巡课记录/班主任沟通" prop="patrolAndCommunicationRecord">
          <el-input v-model="trackingForm.patrolAndCommunicationRecord" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="学员学习情况" prop="studentLearningStatus">
          <el-input v-model="trackingForm.studentLearningStatus" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="关注学员处理方案" prop="studentAttentionProcessingPlan">
          <el-input v-model="trackingForm.studentAttentionProcessingPlan" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTrackingForm">确 定</el-button>
          <el-button @click="cancelTrackingForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="考勤" v-model="attendance_open" width="500px" fullscreen>
      <el-form ref="attendanceFormRef" :model="attendanceForm" :rules="rules" label-width="180px">
        <el-form-item :label="stu.studentName" v-for="stu in studentAttendanceList" :key="stu.id">
          <el-col :span="8">
            <el-radio-group v-model="stu.attendanceStatus" style="width: 200px">
              <el-radio :label="dict.value" v-for="dict in ya_attendance_status" :key="dict.value">{{
                  dict.label
                }}
              </el-radio>
            </el-radio-group>
          </el-col>

          <el-col :span="8">
            <el-input
              type="textarea"
              :rows="1"
              placeholder="备注信息"
              v-model="stu.remark">
            </el-input>
          </el-col>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAttendanceForm">确 定</el-button>
          <el-button @click="cancelAttendanceForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.el-table .warning-row {
  background: #34bfa3;
}

.el-table .success-row {
  background: #f0f9eb;
}

.el-table .yellow-row {
  background: #e6a700;
}
</style>

<script setup>
import {ref, reactive, onMounted, getCurrentInstance} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Refresh, Plus, Scissor, Calendar, Delete} from '@element-plus/icons-vue'

import {
  clearConfig,
  addWorkday,
  addHoliday,
  previewTeachingPlan,
  listAllPlan,
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan
} from "@/api/teaching/teaching_plan";
import {listClass} from "@/api/teaching/class";
// import { listTeaching_tracking, getTeaching_tracking, delTeaching_tracking, addTeaching_tracking, updateTeaching_tracking } from "@/api/teaching/teaching_tracking";
// import {listAllStudent } from "@/api/teaching/student";
// import {listAttendance, updateAttendance} from "@/api/teaching/attendance";
// import {getCompletion, queryDailyInterviewList,queryDailyInterviewListById, updateQualified} from "@/api/teaching/daily_tasks";

// 获取当前实例
const {proxy} = getCurrentInstance()
const {
  sys_stage,
  ya_weekday,
  ya_attendance_status,
  ya_task_status,
  ya_task_qualified
} = proxy.useDict('sys_stage', "ya_weekday", "ya_attendance_status", "ya_task_status", "ya_task_qualified")

// 定义响应式数据
const drawer = ref(false)
const direction = ref('ltr')
const interviewList = ref([])
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const planId = ref(null)
const completionList = ref([])
const completionOpen = ref(false)
const completionLoading = ref(false)
const completionForm = reactive({})
const studentAttendanceList = ref([])
const classesList = ref([])
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const planList = ref([])
const title = ref("")
const open = ref(false)
const tracking_open = ref(false)
const attendance_open = ref(false)
const trackingForm = reactive({})
const attendanceForm = reactive({})
const generationDisabled = ref(true)
const planAllList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 180,
  date: null,
  day: null,
  courseContent: null,
  className: null,
  stage: null
})

// 表单参数
const form = reactive({
  className: undefined,
  stage: undefined,
  beginDate: ""
})

const interviewForm = reactive({})

// 表单校验规则
const rules = {
  date: [
    {required: true, message: "日期不能为空", trigger: "blur"}
  ],
  day: [
    {required: true, message: "第几天不能为空", trigger: "blur"}
  ],
  courseContent: [
    {required: true, message: "授课内容不能为空", trigger: "blur"}
  ],
  remarks: [
    {required: true, message: "备注事项不能为空", trigger: "blur"}
  ],
  className: [
    {required: true, message: "班级名字不能为空", trigger: "blur"}
  ],
  class_id: [{
    required: true,
    message: '请选择班级',
    trigger: 'change'
  }],
  stage: [{
    required: true,
    message: '请选择阶段',
    trigger: 'change'
  }],
  beginDate: [{
    required: true,
    message: '请选择起始日期',
    trigger: 'change'
  }]
}

// 表单引用
const queryFormRef = ref(null)
const completionFormRef = ref(null)
const formRef = ref(null)
const trackingFormRef = ref(null)
const attendanceFormRef = ref(null)
const answerRefs = ref({})

// 字典数据
const dict = reactive({
  type: {
    // ya_attendance_status: [],
    // ya_weekday: [],
    // ya_task_status: [],
    // ya_task_qualified: []
  }
})

// 方法定义
const handleClose = (done) => {
  done()
}

const checkInterview = (row) => {
  // queryDailyInterviewListById(row.id).then(response => {
  //   interviewList.value = response.rows
  //   drawer.value = true
  // })
}

const preList = (url) => {
  return url.split(",")
}

const cancelCompletion = () => {
  completionOpen.value = false
  resetDailyTask()
}

const updateQualified = (row) => {
  let dailyTaskId = row.id
  let qualified = row.qualified
  // updateQualified({dailyTaskId, qualified}).then(response => {
  //   ElMessage.success("更新成功")
  // }).catch(err => {
  //   ElMessage.error("更新失败")
  // })
}

const resetDailyTask = () => {
  Object.assign(completionForm, {
    date: null,
    status: null,
    studentName: null,
    classesId: null,
  })
  if (completionFormRef.value) {
    completionFormRef.value.resetFields()
  }
}

const checkDailyTask = (row) => {
  if (row.date) {
    resetDailyTask()
    completionForm.date = row.date
    completionForm.classesId = row.classesId
  }
  completionLoading.value = true
  // getCompletion(completionForm).then(response => {
  //   completionList.value = response.rows
  //   completionOpen.value = true
  //   completionLoading.value = false
  // })
}

const submitAttendanceForm = () => {
  // updateAttendance(studentAttendanceList.value, classesId.value).then(response => {
  //   ElMessage.success("修改成功")
  //   attendance_open.value = false
  //   getList()
  // })
}

const submitTrackingForm = () => {
  if (trackingFormRef.value) {
    trackingFormRef.value.validate((valid) => {
      if (valid) {
        // updateTeaching_tracking(trackingForm).then(response => {
        //   ElMessage.success("修改成功")
        //   tracking_open.value = false
        //   getList()
        // })
      }
    })
  }
}

const handleAddTracking = (row) => {
  resetTrackingForm()
  title.value = "编辑教学跟踪信息"
  tracking_open.value = true

  // getTeaching_tracking(row.date, row.classesId).then(response => {
  //   if (response.data) {
  //     Object.assign(trackingForm, response.data)
  //   } else {
  //     trackingForm.teachingPlanId = row.id
  //     trackingForm.date = row.date
  //     trackingForm.classesId = row.classesId
  //   }
  // })
}

const handleAddAttendance = (row) => {
  resetTrackingForm()
  // classesId.value = row.classesId
  attendance_open.value = true
  //查询出这个班所有学生
  // listAttendance({"classesId": row.classesId, "date": row.date}).then(response => {
  //   //radio默认值是string，需要将int转string
  //   response.rows.forEach(stu => {
  //     stu.attendanceStatus = stu.attendanceStatus + ""
  //     //设置默认考勤日期
  //     stu.date = row.date
  //   })
  //   studentAttendanceList.value = response.rows
  // })
}

// 表单重置
const resetTrackingForm = () => {
  Object.assign(trackingForm, {
    id: null,
    teachingPlanId: null,
    unfinishedHomeworkAndUnfeedbackList: null,
    leaveNumber: null,
    lateNumber: null,
    patrolAndCommunicationRecord: null,
    studentLearningStatus: null,
    studentAttentionProcessingPlan: null
  })
  if (trackingFormRef.value) {
    trackingFormRef.value.resetFields()
  }
}

// 表单重置
const resetAttendanceForm = () => {
  // attendanceStatusList.value = []
  if (attendanceFormRef.value) {
    attendanceFormRef.value.resetFields()
  }
}

const getClassesList = () => {
  listClass().then(response => {
    classesList.value = response.rows
  })
}

const isHoliday = (row) => {
  if (row.courseContent === '自习' || row.courseContent.includes('节') || row.courseContent.includes('休息')) {
    return true
  } else {
    return false
  }
}

const tableRowClassName = ({row, rowIndex}) => {
  if (row.courseContent === '自习') {
    return 'yellow-row'
  } else if (row.courseContent.includes('节') || row.courseContent.includes('休息')) {
    return 'warning-row'
  } else {
    return 'success-row'
  }
  return ''
}

/** 查询教学计划列表 */
const getList = () => {
  loading.value = true
  listPlan(queryParams).then(response => {
    planList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 取消按钮
const cancelTrackingForm = () => {
  tracking_open.value = false
  resetTrackingForm()
}

const cancelAttendanceForm = () => {
  attendance_open.value = false
  resetAttendanceForm()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: null,
    date: null,
    day: null,
    courseContent: null,
    remarks: null,
    className: null,
    stage: null,
    beginDate: ""
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
  planAllList.value = []
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAddPlan = () => {
  reset()
  open.value = true
  title.value = "添加教学计划"
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const id = row.id || ids.value
  getPlan(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改教学计划"
  })
}

/** 提交按钮 */
const submitForm = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.id != null) {
          updatePlan(form).then(response => {
            ElMessage.success("修改成功")
            open.value = false
            getList()
          })
        } else {
          addPlan(form).then(response => {
            ElMessage.success("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }
}

/** 删除按钮操作 */
const handleDelete = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请至少选择一条记录进行删除");
    return;
  }
  ElMessageBox.confirm(
    '删除后相关的数据不会有影响，可以删除后重新创建！是否确认删除这些教学计划？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const promises = ids.value.map(id => delPlan(id));
    Promise.all(promises)
      .then(() => {
        ElMessage.success("删除成功");
        planAllList.value = [];
        // getList();
        queryTeachingPlan();
      })
      .catch(err => {
        ElMessage.error("删除失败：" + err.message);
      });
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
}

/** 导出按钮操作 */
const handleExport = () => {
  // proxy.download('teaching/plan/export/plan', {
  //   ...queryParams
  // }, `plan_${new Date().getTime()}.xlsx`)
}

const handleConfirm = () => {
  /*let data = {
    teachingPlanList: planAllList.value,
  }
  Object.assign(data, form)
  addPlan(data).then(response => {
    ElMessage.success("新增成功")
    open.value = false
    getList()
  })*/
  // 逐个添加教学计划

  /*const promises = planAllList.value.map(plan => {
    return addPlan(plan);
  });

  Promise.all(promises).then(response => {
    ElMessage.success("新增成功")
    open.value = false
    getList()
  }).catch(error => {
    ElMessage.error("新增失败: " + error.message)
  });*/

  // 使用 Promise.allSettled 来处理部分成功的情况
  const promises = planAllList.value.map(plan => {
    return addPlan(plan).then(response => {
      return {status: 'success', data: response, plan: plan};
    }).catch(error => {
      // 判断是否是因为重复数据导致的错误
      if (error.message && error.message.includes('已存在')) {
        console.log(`教学计划日期 ${plan.date} 已存在，跳过添加`);
        return {status: 'skipped', plan: plan, reason: 'duplicate'};
      }
      // 其他错误
      console.error("添加教学计划失败:", error);
      return {status: 'error', plan: plan, error: error};
    });
  });

  Promise.allSettled(promises).then(results => {
    let successCount = 0;
    let skipCount = 0;
    let errorCount = 0;

    results.forEach(result => {
      if (result.status === 'fulfilled') {
        const value = result.value;
        if (value.status === 'success') {
          successCount++;
        } else if (value.status === 'skipped') {
          skipCount++;
        } else if (value.status === 'error') {
          errorCount++;
        }
      } else {
        errorCount++;
      }
    });

    let message = "";
    if (successCount > 0) {
      message += `成功添加${successCount}条教学计划`;
    }
    if (skipCount > 0) {
      if (message) message += "，";
      message += `${skipCount}条已存在记录被跳过`;
    }
    if (errorCount > 0) {
      if (message) message += "，";
      message += `${errorCount}条添加失败`;
    }

    if (errorCount === results.length) {
      ElMessage.error("所有教学计划添加失败: " + message);
    } else if (errorCount > 0) {
      ElMessage.warning("部分教学计划添加完成: " + message);
    } else {
      ElMessage.success("教学计划添加完成: " + message);
    }

    open.value = false;
    getList();
  });
}

const queryTeachingPlan = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        listAllPlan(form).then(response => {
          planAllList.value = response.rows
          if (response.rows.length === 0) {
            generationDisabled.value = false
            ElMessage.success("该班级还未创建教学计划！")
          } else {
            generationDisabled.value = true
            //获取第一天计划日期
            form.beginDate = response.rows[0].date
            ElMessage.warning("该班级已经创建教学计划，请细心修改！")
          }
        })
      }
    })
  }
}

const handleClearConfig = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        clearConfig(form).then(response => {
          planAllList.value = response.rows
        })
      }
    })
  }
}

const handlePreviewTeachingPlan = () => {
  previewTeachingPlan(form).then(response => {
    planAllList.value = response.data
    if (response.data.length === 0) {
      generationDisabled.value = false
      ElMessage.success("该班级还未创建教学计划！")
    }
  }).catch(error => {
    ElMessage.error(error.response.data.msg)
  })
}

const handleAddHoliday = (i, row, type) => {
  row.beginDate = form.beginDate
  row.type = type
  addHoliday(row).then(response => {
    planAllList.value = response.rows
    if (response.rows.length == 0) {
      generationDisabled.value = false
      ElMessage.success("该班级还未创建教学计划！")
    }
  })
}

const handleAddWorkday = (i, row) => {
  row.beginDate = form.beginDate
  addWorkday(row).then(response => {
    planAllList.value = response.rows
    if (response.rows.length == 0) {
      generationDisabled.value = false
      ElMessage.success("该班级还未创建教学计划！")
    }
  })
}

const changeStudentList = (value) => {
  // 实现具体逻辑
}

const parseTime = (time, pattern) => {
  // 实现时间解析逻辑
  return time
}

// 生命周期钩子
onMounted(() => {
  getList()
  getClassesList()
})
</script>
